/**
 * 作者:李杰
 * email: maillijie@gmail.com
 */
package com.javainfo.actions.admin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.rest.DefaultHttpHeaders;
import org.apache.struts2.rest.HttpHeaders;

import com.javainfo.dto.PageDto;
import com.javainfo.entity.ArticleCategory;
import com.javainfo.exception.AppException;
import com.javainfo.simpledto.ArticleDto;
import com.javainfo.util.JavaInfoActionSupport;

@Results( {})
public class CategoryCtrl extends JavaInfoActionSupport{

	/** serialVersionUID */
	private static final long serialVersionUID = 1L;

	public HttpHeaders create() {
		//获取画面输入的值，转换成service层需要的Dto
		String categoryName = getRequest().getParameter("categoryName");
		ArticleCategory category = new ArticleCategory();
		category.setCategoryName(categoryName);
		
		//判断权限并执行
		getServiceFactory().getCategoryService().add(category);
		addActionMessage("新建分类成功!");
		setRedirectUrl("admin/anyone/categoryManage");
		return new DefaultHttpHeaders("urlhandler");
	}

	public String index() {
		setModel(getServiceFactory().getCategoryService().getCategoryList());
		return INDEX;
	}
	
	@SuppressWarnings("finally")
	public HttpHeaders destroy() {
		ArticleCategory category = new ArticleCategory();
		category.setId(Integer.valueOf(getId()));
		try {
			getServiceFactory().getCategoryService().delete(category);
			addActionMessage("删除分类成功!");
		} catch (AppException e) {
			addActionMessage(e.getMessage());
		} finally {
			setRedirectUrl("admin/anyone/categoryManage");
			return new DefaultHttpHeaders("urlhandler");
		}
	}

	public HttpHeaders update() {
		return null;
	}

	public HttpHeaders show() {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("category", getServiceFactory().getCategoryService()
				.getCategoryInfo(getId()));
		List<ArticleDto> articleList = getServiceFactory().getCategoryService()
				.getCategoryArticles(getId());
		setPageDto(PageDto.init(articleList.size(), getPageDto()));
		articleList = articleList.subList(getPageDto().getStartRow(),
				getPageDto().getEndRow());
		model.put("articles", articleList);
		setModel(model);
		return new DefaultHttpHeaders(SHOW);
	}
	
	/**
	 * 在特定分类里面创建新帖子
	 * @return
	 */
	public String newArticle() {
		setModel(getServiceFactory().getCategoryService().getById(
				Integer.valueOf(getId())));
		return "newArticle";
	}
}
